package com.mineoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mineoj.common.ErrorCode;
import com.mineoj.constant.CommonConstant;
import com.mineoj.exception.BusinessException;
import com.mineoj.exception.ThrowUtils;
import com.mineoj.mapper.NewsCommentMapper;
import com.mineoj.mapper.NewsThumbMapper;
import com.mineoj.model.dto.news.NewsQueryRequest;
import com.mineoj.model.entity.*;
import com.mineoj.model.entity.News;
import com.mineoj.model.vo.NewsVO;
import com.mineoj.model.vo.UserVO;
import com.mineoj.service.NewsService;
import com.mineoj.mapper.NewsMapper;
import com.mineoj.service.UserService;
import com.mineoj.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 明月
* @description 针对表【news(新鲜事)】的数据库操作Service实现
* @createDate 2025-04-11 19:39:27
*/
@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News>
    implements NewsService{
    @Resource
    private UserService userService;

    @Resource
    private NewsMapper newsMapper;

    @Resource
    private NewsThumbMapper newsThumbMapper;

    @Resource
    private NewsCommentMapper newsCommentMapper;

    /**
     * 校验新鲜事信息
     * @param news
     * @param add 是否为创建校验
     */
    @Override
    public void validNews(News news, boolean add) {
        if (news == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = news.getTitle();
        String content = news.getContent();
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content), ErrorCode.PARAMS_ERROR);
        }
        if(StringUtils.isNoneBlank(title) && title.length() > 80){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if(StringUtils.isNoneBlank(content) && content.length() > 8192){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }

    }

    /**
     * 获取查询包装类（用户根据哪些字段查询，根据前端传来的请求对象，得到 mybatis 框架支持的查询 QueryWrapper 类）
     * 构建动态查询条件的方法，主要用于数据库查询（基于MyBatis Plus的QueryWrapper）
     * @param newsQueryRequest 新鲜事查询请求
     * @return
     */
    @Override
    public QueryWrapper<News> getQueryWrapper(NewsQueryRequest newsQueryRequest) {
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        if (newsQueryRequest == null) {
            return queryWrapper;
        }

        Long id = newsQueryRequest.getId();
        String title = newsQueryRequest.getTitle();
        String content = newsQueryRequest.getContent();
        Long userId = newsQueryRequest.getUserId();
        String sortField = newsQueryRequest.getSortField();
        String sortOrder = newsQueryRequest.getSortOrder();
        String searchText = newsQueryRequest.getSearchText();

        // 拼接查询条件
        // 当参数非空时，添加 LIKE 条件。SQL 类似 WHERE title LIKE '%Java%'。

        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);

        // 精确匹配
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);

        // 排序逻辑
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 将新鲜事对象转换为新鲜事视图对象，并关联查询用户信息。
     * @param news
     * @param request
     * @return
     */
    @Override
    public NewsVO getNewsVO(News news, HttpServletRequest request) {
        NewsVO newsVO = NewsVO.objToVo(news);
        // 1. 关联查询用户信息
        Long userId = news.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        newsVO.setUserVO(userVO);
        return newsVO;
    }

    /**
     * 将新鲜事转换为新鲜事视图列表，并关联查询用户信息。
     * @param newsPage
     * @param request
     * @return
     */
    @Override
    public Page<NewsVO> getNewsVOPage(Page<News> newsPage, HttpServletRequest request) {
        List<News> newsList = newsPage.getRecords();
        Page<NewsVO> newsVOPage = new Page<>(newsPage.getCurrent(), newsPage.getSize(), newsPage.getTotal());
        if (CollectionUtils.isEmpty(newsList)) {
            return newsVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = newsList.stream().map(News::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<NewsVO> newsVOList = newsList.stream().map(news -> {
            NewsVO newsVO = NewsVO.objToVo(news);
            Long userId = news.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            newsVO.setUserVO(userService.getUserVO(user));
            return newsVO;
        }).collect(Collectors.toList());
        newsVOPage.setRecords(newsVOList);
        return newsVOPage;
    }

    @Override
    @Transactional
    public boolean deleteById(long id) {
        if (newsMapper.deleteById(id) > 0) {
            //删除点赞
            newsThumbMapper.delete(new QueryWrapper<NewsThumb>().eq("newsId", id));
            //删除评论
            newsCommentMapper.delete(new QueryWrapper<NewsComment>().eq("newsId", id));

        }
        return true;
    }

}




